package advanced.thread;


/**
 * 线程协作
 * 生产者消费者模式
 */
public class L12 {
    public static void main(String[] args) {
        SynContainer container = new SynContainer();
        new Productor(container).start();
        new Consumer(container).start();
    }
}

class Productor extends Thread {
    SynContainer container;

    public Productor(SynContainer container) {
        this.container = container;
    }

    @Override
    public void run() {
        //生产
        for (int i = 0; i < 100; i++) {
            System.out.println("生产第" + i + "个馒头");
            container.push(new Stemedbun(i));
        }
    }
}

class Consumer extends Thread {
    private SynContainer container;

    public Consumer(SynContainer container) {
        this.container = container;
    }

    @Override
    public void run() {
        //消费

        for (int i = 0; i < 1000; i++) {
            System.out.println("消费第" + container.pop().getId() + "个馒头");

        }
    }
}

/**
 * 馒头类
 */
class Stemedbun {
    private int id;

    public int getId() {
        return this.id;
    }

    public Stemedbun(int id) {
        this.id = id;
    }
}

class SynContainer {
    Stemedbun[] buns = new Stemedbun[10];
    int count = 0;

    //存储
    public synchronized void push(Stemedbun bun) {
        //只有容器有空余空间可以生产
        if (count == buns.length) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        buns[count++] = bun;
        //存在数据了可以消费了
        this.notifyAll();

    }

    //获取
    public synchronized Stemedbun pop() {
        //没有数据时,不能进行消费
        if (count == 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        count--;
        Stemedbun bun = buns[count];

        this.notifyAll();//存在空间了, 可以进行生产了
        return bun;
    }
}